// pages/main.js
const app = getApp();

import { server } from '../../config/server.js';
import { task } from '../../server/task';

Page({
    /**
     * 页面的初始数据
     */
    data: {
        server_addr: server.server_addr,
        top_line_background_image: `${server.server_addr}/images/mainPageBackGroundImage.png`,
        Postgraduate: '2025-12-21',
        remainDays: 0,
        testYear: 0,
        // likeNum: 200,
        // shareNum: 300,
        sentenceText: '满怀激情地投入到对事理的探究中来,至于建筑变成了自然而然的结果。',
        weekDays: [],
        domainList: [
            {
                name: "院校",
                imgSrc: `${server.server_addr}/qianduantupian/images/domain/院校.png`,
                jmpFunc: "jmpSchoolPage"
            }, {
                name: "资讯",
                imgSrc: `${server.server_addr}/qianduantupian/images/domain/咨讯.png`,
                jmpFunc: "jmpzixunPage"
            }, {
                name: "自习室",
                imgSrc: `${server.server_addr}/qianduantupian/images/domain/百科.png`,
                jmpFunc: "jmpStudyPage"
            }, {
                name: "参考书",
                imgSrc: `${server.server_addr}/qianduantupian/images/domain/参考书.png`,
                jmpFunc: "jmpBookPage"
            }, {
                name: "题库",
                imgSrc: `${server.server_addr}/qianduantupian/images/domain/题库.png`,
                jmpFunc: "jmpQuestionBankPage"
            }, {
                name: "背单词",
                imgSrc: `${server.server_addr}/qianduantupian/images/domain/背单词.png`,
                jmpFunc: "jmpReciteWordPage"
            }
        ],
        taskList: [],
        showAddTaskBox: false,
        taskName: '',
        taskDesc: '',
        taskCount: 30,
        lastTaskCount: 30,
        taskInfoBox: {
            isshow: false,
            taskId: 0,
            taskName: '',
            taskDesc: '',
            completed: '',
            taskCount: 0,
            checked: 0,
            progress: '',
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('topbg', this.data.top_line_background_image);
        this.generateWeekCalendar();    // 生成周历

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        console.log('onshow');
        this.getMyTaskListAndShow();      // 获取任务列表
        this.showRemainDays();
        if (app.globalData.getTaskListFlag == 1) {
            // 发起网络请求，获取任务列表
            this.getMyTaskListAndShow();
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    // 计算考研年份和考研天数差
    showRemainDays() {
        const nowTime = Date.now();
        const Postgraduate = new Date(this.data.Postgraduate);
        let remainDays = Math.ceil((Postgraduate - nowTime) / (24 * 60 * 60 * 1000));
        let testYear = Postgraduate.getFullYear();
        this.setData({ remainDays, testYear });
    },

    /*
     * 生成周历的函数
     */
    generateWeekCalendar() {
        const nowTime = Date.now() - 259200000;  // 获取当前时间戳
        const weekDayName = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];

        const weekDays = [];
        for (let i = 0; i < 7; i++) {
            let date = new Date(nowTime + 86400000 * i);
            let day = date.getDate();                  // 获取当天的日期
            let dayName = weekDayName[date.getDay()];  // 获取星期几的文字表示
            weekDays.push({
                date: day,    // 日期数字
                day: dayName  // 星期几的英文表示
            });
        }

        this.setData({ weekDays }); // 更新数据到界面
    },
    /*
     * 8个主要功能跳转函数
     */
    jmpSchoolPage() {
        // 院校
        wx.navigateTo({
            url: '/pages/school/school'
        });
    },
    jmpzixunPage() {
        // 资讯
        wx.navigateTo({
            url: '/pages/zixun/zixun'
        });
    },
    jmpStudyPage() {
        wx.switchTab({
            url: '/pages/study/study'
        });
    },
    jmpBookPage() {
        wx.navigateTo({
            url: '/pages/book/book'
        });
    },
    jmpQuestionBankPage() {
        wx.navigateTo({
            url: '/pages/questionBank/questionBank'
        });
    },
    jmpReciteWordPage() {
        wx.navigateTo({
            url: '/pages/reciteWord/reciteWord'
        });
    },
    /*
     * 跳转到添加任务按扭的函数
     */
    jmpAddTaskPage() {
        wx.navigateTo({
            url: '/pages/addTask/addTask',
        });
    },
    /*
     * 获取任务列表并展示到页面中
     */
    getMyTaskListAndShow() {
        task.getTaskList().then(res => {
            let taskList = [];
            for (let item of res.data.taskList) {
                let tmp = {
                    id: item.id,
                    uid: item.uid,
                    taskName: item.taskName,
                    taskDescription: item.taskDescription,
                    completed: item.completed,
                    count: item.count,
                    checked: item.checked,
                    progress: `${parseInt(parseInt(item.checked) / parseInt(item.count) * 100)}%`
                };
                taskList.push(tmp);
            }
            this.setData({ taskList });
        }).catch((err) => {
            wx.showToast({
                title: '请检查网络连接',
            });
        });
    },
    jmpSignInPage() {
        wx.navigateTo({
            url: '/pages/signin/signin',
        })
    },
    // 输入任务名称的函数
    inputTaskNameFunc(e) {
        this.setData({
            taskName: e.detail.value
        });
    },
    // 输入任务描述的函数
    inputTaskDescFunc(e) {
        this.setData({
            taskDesc: e.detail.value
        });
    },
    // 输入任务次数的函数
    inputTaskCountFunc(e) {
        let a = e.detail.value;
        try {
            a = parseInt(a);
            this.setData({
                taskCount: a
            });
        } catch (err) {
            console.log(err);
            this.setData({
                taskCount: this.data.lastTaskCount
            });
        }
    },
    // 打开添加任务的窗口
    openAddTaskBox() {
        this.setData({
            showAddTaskBox: true
        });
    },
    // 关闭添加任务的窗口
    closeAddTaskBox() {
        this.setData({
            taskName: '',
            taskDesc: '',
            taskCount: 30,
            lastTaskCount: 30,
            showAddTaskBox: false
        });
    },
    // 添加任务窗口的格式判断函数
    checkAddTaskFunc(taskName, taskDesc, taskCount) {
        // 判空
        if (!taskName) {
            wx.showToast({
                title: '任务名称不能为空',
                icon: 'none',
                duration: 1000
            });
            return false;
        }
        if (!taskDesc) {
            wx.showToast({
                title: '任务描述不能为空',
                icon: 'none',
                duration: 1000
            });
            return false;
        }
        if (!taskCount) {
            wx.showToast({
                title: '任务次数不能为0',
                icon: 'none',
                duration: 1000
            });
            return false;
        }
        // 尝试转换整数
        taskCount = parseInt(taskCount);
        if (taskCount === NaN) {
            return false;
        }
        // 判断整数范围是否合法
        if (taskCount <= 0 || taskCount > 5000) {
            wx.showToast({
                title: '任务次数为非法值',
                icon: 'none',
                duration: 1000
            });
            return false;
        }
        return true;
    },
    // 提交添加任务的函数
    commitAddTaskBox() {
        // 获取用户输入的值
        let taskName = this.data.taskName;
        let taskDesc = this.data.taskDesc;
        let taskCount = this.data.taskCount;
        // 判断用户输入是否合法
        let flag = this.checkAddTaskFunc(taskName, taskDesc, taskCount);
        if (!flag) return ;
        // 调用后端接口
        task.addTask(taskName, taskDesc, taskCount).then((res) => {
            if (!res.success) {
                wx.showToast({
                    title: '任务添加失败',
                    icon: 'none',
                    duration: 1000
                });
                return ;
            }
            this.closeAddTaskBox();
            wx.showToast({
                title: '任务添加成功',
                icon: 'none',
                duration: 1000
            });
            this.getMyTaskListAndShow();
        }).catch((err) => {
            console.log(err);
            wx.showToast({
                title: '请检查网络连接',
                icon: 'none',
                duration: 1000
            });
        });
    },
    openTaskInfoBox(e) {
        let task = e.currentTarget.dataset.item;
        let newTaskInfoBox = this.data.taskInfoBox;
        newTaskInfoBox.isshow = true;
        newTaskInfoBox.taskId = task.id;
        newTaskInfoBox.taskName = task.taskName;
        newTaskInfoBox.taskDesc = task.taskDescription;
        newTaskInfoBox.completed = task.completed;
        newTaskInfoBox.taskCount = task.count;
        newTaskInfoBox.checked = task.checked;
        newTaskInfoBox.progress = task.progress;

        this.setData({
            taskInfoBox: newTaskInfoBox
        });
    },
    closeTaskInfoBox() {
        let newTaskInfoBox = this.data.taskInfoBox;
        newTaskInfoBox.isshow = false;
        this.setData({
            taskInfoBox: newTaskInfoBox
        });
    },
    setTaskComplete() {
        if (this.data.taskInfoBox.completed) {
            wx.showToast({
                title: '任务已完成',
                icon: 'none',
                duration: 1000
            });
            return;
        }
        task.setTaskComplete(this.data.taskInfoBox.taskId)
            .then((res) => {
                wx.showToast({
                    title: '任务完成',
                    icon: 'none',
                    duration: 1000
                });
                this.closeTaskInfoBox();
                let allTask = this.data.taskList;
                for (let i = 0; i < allTask.length; i++) {
                    let item = allTask[i];
                    if (item.id == this.data.taskInfoBox.taskId) {
                        allTask[i].completed = true;
                        allTask[i].checked++;
                        allTask[i].progress = `${parseInt(parseInt(item.checked) / parseInt(item.count) * 100)}%`;
                    }
                }
                this.setData({
                    taskList: allTask
                });
            }).catch((err) => {
                console.log(err);
                wx.showToast({
                    title: '请检查网络连接',
                    icon: 'none',
                    duration: 1000
                });
            });
    }
});